package com.maoye.ossp.sys.quartz.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.quartz.entity.SysQuartzParameter;
import com.maoye.ossp.sys.quartz.service.ParameterService;

@Controller()
@RequestMapping(value = "sys/quartz/param")
public class ParaMeterController extends BaseController {

	@Resource
	private ParameterService service;

	@RequestMapping(value = "getParaMeterByJobID")
	public String getParaMeterByJobID(HttpServletRequest request,
			HttpServletResponse response, Long job_id, ModelMap modelMap) {

		List<SysQuartzParameter> list = service.getParameterByJobID(job_id);
		modelMap.put("job_id", job_id);
		modelMap.put("list", list);

		return "/sys/quartz/addParam";
	}

	@RequestMapping(value = "addJobParameter")
	public String addJobParameter(HttpServletRequest request,
			HttpServletResponse response,
			RedirectAttributes redirectAttributes, String jsonStr, Long job_id,
			ModelMap modelMap) {

		List<SysQuartzParameter> list = new ArrayList<SysQuartzParameter>();
		SysQuartzParameter parameter = null;
		JSONArray jsonArray = JSONArray.fromObject(jsonStr);
		if (jsonArray.size() > 0) {
			for (int i = 0; i < jsonArray.size(); i++) {
				JSONObject json = (JSONObject) jsonArray.get(i);
				parameter = new SysQuartzParameter();
				parameter.setId(idGenerator.getUId());
				parameter.setJob_id(job_id);
				parameter.setName(json.getString("name"));
				parameter.setType(json.getString("type"));
				parameter.setValue(json.getString("value"));
				list.add(parameter);
			}
		}else{
			parameter = new SysQuartzParameter();
			parameter.setJob_id(job_id);
			list.add(parameter);
		}
		service.addJobParameter(list);
		addMessage(redirectAttributes, "参数已保存");
		return "redirect:getParaMeterByJobID?job_id=" + job_id;
	}
}
